import Taro, { Component } from '@tarojs/taro'
import { View, Image, Input} from '@tarojs/components'
import { DNavBar, DItemError } from '@/components'
import { AtIndexes, AtList, AtListItem,AtSearchBar } from 'taro-ui'
import http from '@/api'
import sdk from '@/common/sdk'
import './choosebrand.scss'

export default class ChoosebrandBox extends Component {
    constructor(props) {
        super(props)
        this.state = {
            arrIcon: require('../../assets/images/icon／基础／01right@2x.png'),
            secondSelect: [],
            list: [],
			vehicleTypeData:false,
            active: 1, // 1:选择品牌 2:选择车系 3:选择型号
            title: '选择品牌',
            itemdata: [],
            firstList: [],
            secondList: [],
            status: false,
            mount: false,
            index: '',
            brandName: '', // 保存第1次点击的品牌名称，后退时显示
			searchVal:''
        }
    }

    componentWillMount() {

        this.httpCarData()
    }


    onClick(e) {
        let { firstList, itemdata, secondList, aaa } = this.state
        let secondSelect = []
        http.brandInformationQueryvnId(e.index.vnId).then(data => {
            data.forEach(item => {
                let index = secondSelect.findIndex(i => i.title == item.manufacturer)
                if (index === -1) {
                    secondSelect.push({
                        title: item.manufacturer,
                        items: [{
                            ...item,
                            name: item.biName
                        }]
                    })
                }
                else {
                    secondSelect[index].items.push({ ...item, name: item.biName })
                }
            })

            let _arr = data
            firstList = []
            secondList = []
            _arr.map((item) => {
                firstList.push({
                    title: item.biName,
                    item
                })
                // item.carModelVOs.map(_item => {
                //     secondList.push({
                //         carModel: _item.biName,
                //         carGuiPrice: _item.maximumPrice,
                //         carModelId: _item.biId,
                //         carSourceType: _item.carSourceType
                //     })
                // })
            })
            this.setState({
                active: 2,
                title: e.index.vbmName,
                firstList,
                brandName: e.index.vbmName,
                secondList,
                secondSelect,
                status: true,
                index: e.index
            }, () => {
                sdk.setTitleInfo(this.state.title)
            })
        })
    }
    onSearch(){
		this.onFirstHandle(0,this.state.searchVal,{items:[{biName:'选择车型'}]},-1)

	}
    onFirstHandle(i, biId, item,vehicleTypeData) {
		vehicleTypeData = vehicleTypeData==-1
        http[vehicleTypeData?'vehicleTypeData':'vehicleTypeDataQuerybiId'](biId).then(data => {
            var secondList = []
			if(vehicleTypeData){
				data=data.list
			}
            data.map((_item, i) => {
                secondList.push({
                    ..._item,
					isSearch:vehicleTypeData,
                    carModel: _item.vtdName || '--',
                    carGuiPrice: (Number(_item.changshangzhidaojia) / 10000).toFixed(2),
                    carModelId: _item.vtdId,
                    carSourceType: _item.nengyuanleixing,
                })
            })
            if (data.length == 0) {
                Taro.showToast({
                    title: "该车系暂无型号",
                    icon: "none"
                })
				if(!vehicleTypeData ){
					 return
				}
            }

            let title = ''
            if (item) {
              title = item.items[i].biName
            }else{
				title = this.state.firstList[i].item.biName
			}

            this.setState({
                active: 3,
				vehicleTypeData,
                title,
                status: true,
                secondList
            }, () => {
                sdk.setTitleInfo(this.state.title)
            })
        })

    }

    onSecondHandle(item) {
		debugger
        Taro.showLoading({
            title: '',
            mask: true
        }).then(() => {
            let { index, itemdata } = this.state
            let carinfo = {
                ...item,
                carDataBrandLogo: item.carBrandLogo,
                carBrandId: item.vnId, //车系
                carBrand: item.pinpai,
                carSeries: item.chexi,
                carSeriesId: item.biId,
                carModel: (!item.isSearch?item.chexi + ' ':'') + item.carModel,
            }
            sessionStorage.setItem("brandList", JSON.stringify(carinfo))
            Taro.showToast({
                title: '已选择车辆',
                duration: 800,
                mask: true
            }).then(() => {
                setTimeout(() => {
                    Taro.hideLoading()
                    Taro.navigateBack({
                        delta: 1
                    })
                }, 1000);
            })
        })
    }

    onClickLeftIcon() {
        let { active } = this.state
        active--
        this.setState({
            active,
            title: this.getTitle(active),
            status: active === 1 ? false : true
        })
    }

    getTitle(status) {
        // this.onClick(e)
        // this.onFirstHandle(i)
        return {
            $1: '选择品牌',
            $2: this.state.brandName,
            $3: '选择型号'
        }[`$${status}`]
    }

    httpCarData(name) {
        http.getCarData().then(data => { })
        let { list } = this.state
        http.vehicleBrandManagement(name||'').then(data => {
            if (!data) {
                return
            }
            // const list = [
            //   {
            //     "createBy": "创建人",
            //     "createTime": "创建时间",
            //     "id": "ID",
            //     "initial": "首字母",
            //     "modifyBy": "修改人",
            //     "modifyTime": "修改时间",
            //     "recStatus": "逻辑删除",
            //     "remark": "备注",
            //     "renewalTime": "更新时间",
            //     "soldStatus": "在售状态：0停售、1在售",
            //     "vbmName": "品牌",
            //     "vnId": "品牌ID",
            //     "vnLogo": "品牌Logo"
            //   }
            // ]
            let _itemdata = [], _list = [], arr = []
            data.map((item, i) => {
                let _item = []

                _list.push({
                    title: item.initial,
                    key: item.initial.split('')[0],
                    items: _item
                })
                _item.push({
                    name: item.vbmName,
                    index: item
                })
            })
            _list.map(item => {
                arr.push(item.key)
            })
            arr = [...new Set(arr)]
            let _arr = []
            for (let i = 0, j = arr.length; i < j; i++) {
                let items = []
                for (let k = 0, l = _list.length; k < l; k++) {
                    if (arr[i] === _list[k].key) {
                        items.push(..._list[k].items)
                    }
                }
                _arr.push({
                    title: arr[i],
                    key: arr[i],
                    items
                })
            }

            _itemdata = data
            this.setState({
                list: _arr,
                itemdata: _itemdata,
                mount: true,
            })
        })
    }
    handleChange (searchVal) {
        this.setState({
          searchVal
        },()=>{
			this.httpCarData(searchVal)
		})
        // 在小程序中，如果想改变 value 的值，需要 `return value` 从而改变输入框的当前值
        return searchVal
      }
	  searchValChange = (val) => {
	    this.setState({ searchVal: val.trim() })
	  }
	  onClear = () => {
	    this.setState({ searchVal: '', active:1},this.httpCarData)
	  }

    render() {

        const { list, title,vehicleTypeData, active, firstList, secondList, status, mount, secondSelect, arrIcon,searchVal } = this.state
        return (
            <View className="b_choosebrand">
                <DNavBar status={status} title={title} onClickLeftIcon={this.onClickLeftIcon.bind(this)}></DNavBar>
                <View className="b_choosebrand__box">
				   {(active === 1||vehicleTypeData) &&<View className="b_search__box t-center">
				   <AtSearchBar value={searchVal}
				                maxLength={80}
				                onChange={this.searchValChange.bind(this)}
								placeholder='搜索车型'
								onConfirm={this.onSearch.bind(this)}
				                onActionClick={this.onSearch.bind(this)}
				                onClear={this.onClear.bind(this)} />

				   </View>}
                    <View className="b_choosebrand__content">
                        {
                            list.length > 0 && active === 1 && <View style='height:100vh'>
                                <AtIndexes
                                    isShowToast={false}
                                    list={list}
                                    onClick={this.onClick.bind(this)}
                                    topKey=""
                                >
                                </AtIndexes>
                            </View>
                        }
                        {
                            /*
                                <AtIndexes
                                    list={secondSelect}
                                    onClick={this.onFirstHandle.bind(this)}
                                >
                                </AtIndexes>
                            */
                            firstList.length > 0 && active === 2 && <View>
                                {
                                    secondSelect && secondSelect.map(item => <View className="b_choosebrand__content_item">
                                        <View className="b_choosebrand__content_top">{item.title}</View>
                                        <View className="b_choosebrand__content_list">
                                            {
                                                item.items.map((item1, i) => <View className="b_choosebrand__content_list_item" onClick={this.onFirstHandle.bind(this, i, item1.biId, item)}>
                                                    <View className="b_choosebrand__content_list_item_left">{item1.name}</View>
                                                    {/* <View className="b_choosebrand__content_list_item_right">
                                                        <View className="number">{item1.vehicleNum}条</View>
                                                        <Image src={arrIcon} className="arr_icon"></Image>
                                                    </View> */}
                                                </View>)
                                            }
                                        </View>
                                    </View>)
                                }
                                {/* <AtList>
                                    {

                                        firstList && firstList.map((item, i) => {
                                            return <AtListItem key={i} onClick={this.onFirstHandle.bind(this, i)} title={item.title} arrow='right' />
                                        })
                                    }
                                </AtList> */}
                                {
                                    firstList.length === 0 && <DItemError></DItemError>
                                }
                            </View>
                        }
                        {
                            secondList.length > 0 && active === 3 && <View>
                                <AtList>
                                    {
                                        secondList && secondList.map((item, i) => {
                                            return <AtListItem key={i} extraText={`${ ((+item.changshangzhidaojia) / 10000) == 0 ? '面议' : ((+item.changshangzhidaojia) / 10000)  + '万' }`} onClick={this.onSecondHandle.bind(this, item)} title={item.carModel || '型号名为空'} />
                                        })
                                    }
                                </AtList>

                            </View>
                        }
                        {
                            list.length === 0 && mount && <DItemError></DItemError>
                        }
                    </View>
                </View>
            </View>
        )
    }
}
